<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="./lib/bootstrap.css">
    <script src="./lib/jquery.js"></script>

</head>

<body>

    <input type="file" name="" id="file1">
    <button id="upLoad">上传文件</button>
    <br>
    <img src="./images/loading.gif" alt="" style="display: none;" id="loading">
    <div class="progress" style="width: 400px; margin: auto;">
        <div id="progress" class="progress-bar progress-bar-striped active" style="width: 0%">
            0% Complete
        </div>
    </div>
    <img src="" alt="" id="img" width="500"> .
    <script>
        //获取文件上传按钮
        $('#upLoad').on('click', function() {
            //获取用户上传的文件列表
            var file1 = $('#file1')[0].files;
            //$('#file1')[0]转化为原生DOM对象

            if (file1.length <= 0) {
                return alert('请选择要上传的文件！');
            }

            var fd = new FormData();
            //将用户选择的文件，添加到 FormData 中
            fd.append('tupian', file1[0]);

            //用jquery.ajax()方法上传文件
            $.ajax({
                method: 'post',
                url: 'http://www.liulongbin.top:3006/api/upload/avatar',
                data: fd,
                contentType: false, //告诉jQuery不要去设置Content-Type请求头使用默认的Content-Type
                processData: false, //不对FormData进行url序列化处理，默认值为true。将数据原样传递给服务器
                success: function(res) {
                    console.log(res);
                    if (res.status == 200) {
                        alert('上传成功！');
                        $('#img').attr('src', 'http://www.liulongbin.top:3006' + res.url);
                    } else {
                        alert('上传失败！');
                    }
                },
            })

        });
        //当有ajax发起时，展示loading图片
        $(document).ajaxStart(function() {
            $('#loading').show();
        });
        //当ajax结束时，隐藏loading图片
        $(document).ajaxStop(function() {
            $('#loading').hide();
        });
    </script>
</body>

</html>